package com.aop.aspect2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 关注点：重复代码
 * 
 * 
 * 用动态代理  织入
 * 
 * 
 * 
 * @author My
 *
 */

@Component
@Aspect
public class TransactionAspect {
	
	@Pointcut("execution(* com.aop.aspect2.*.*(..))")
	public void printTitle(){}
	
	@Before(value="printTitle()")
	public void Tranq(){
		System.out.println("手写的切面开启事务");
	}
	
	@After(value="printTitle()")
	public void commit(){
		System.out.println("手写的切面提交事务");
		
	}
	
	@Around(value="printTitle()")
	public void round(ProceedingJoinPoint pjp) throws Throwable{
		
		//拿到sql
		Object proceed = pjp.proceed();
		String sql=(String)proceed;
		
		//参数  数组
		Object[] args = pjp.getArgs();
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/spring", "root", "root");
		con.setAutoCommit(false);
		PreparedStatement ps = con.prepareStatement(sql);
		
		ps.setString(1, (String)args[0]);
		ps.setInt(2, (int)args[1]);
		
		int resutlNum = ps.executeUpdate();
		
		con.commit();
		
	}

}
